package cn.buildoncloud.labor.workermanapplet.business.modules.controller;

import cn.buildoncloud.labor.workermanapplet.business.modules.services.LaborServiceCompanyService;
import cn.buildoncloud.labor.workermanapplet.common.Constant;
import cn.buildoncloud.labor.workermanapplet.common.base.Result;
import cn.buildoncloud.labor.workermanapplet.dto.LaborServiceCompanyDTO;
import cn.buildoncloud.labor.workermanapplet.util.HttpUtil;
import cn.buildoncloud.labor.workermanapplet.util.OCRUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.entity.Record;
import org.nutz.http.Http;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 劳务公司管理
 * Description: cn.buildoncloud.labor.workermanapplet.business.modules.controller
 * Created by CuiZibo on 2018/11/13 11:23
 */
@RestController
@RequestMapping("/laborServiceCompany")
public class LaborServiceCompanyController {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private Dao dao;

    @Autowired
    private LaborServiceCompanyService laborServiceCompanyService;

    @Value("${webSystemIP}")
    private String webSystemIP;

    /**
     * 模糊查询分公司下的劳务公司
     * @param unitId
     * @param key
     * @return
     */
    @RequestMapping("/listByUnit")
    public Object listByUnit(@RequestParam(value = "unitId") String unitId,
                             @RequestParam(value = "key", required = false) String key) {
        try {

            List<LaborServiceCompanyDTO> list = laborServiceCompanyService.listByUnit(unitId,key);
            return Result.success(Constant.API_OPERATION_SUCCESS, list);
        } catch (Exception e) {
            log.error("laborServiceCompany/listByUnit: ", e);
            return Result.error(Constant.API_OPERATION_FAILED);
        }
    }

    /**
     * OCR识别营业执照
     * 判断是否同一个公司  是否重复注册 劳务公司
     * @param base64File
     * @param unitId  分公司id
     * @return
     */
    @RequestMapping("/ocrBizLicense")
    public Object ocrBizLicense(@RequestParam("base64File") String base64File,@RequestParam("unitId") String unitId ) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            HashMap<String, Object> data = new HashMap<>();
            //解析之后返回的数据
            Result result = OCRUtil.ocrBizLicense(base64File);
            //获取信用代码
            //判断result.data是否为空
            if(result.getData()!=null){
              String dataJsonStr=objectMapper.writeValueAsString(result.getData());
              try{

                  data=objectMapper.readValue(dataJsonStr,HashMap.class);
                 //判断第一级 ocrInfo 是否为null
                  if(data.get("ocrInfo")!=null){
                      //获取data中第一级
                      //转成map
                      HashMap<String,Object> ocrInfoMap = (HashMap) data.get("ocrInfo");
                      //获取 ocrInfo 中的data
                      if(ocrInfoMap.get("data")!=null){
                          //data 中的第二级
                          HashMap<String,Object> data1 = (HashMap<String, Object>) ocrInfoMap.get("data");
                          String dutyNum = (String) data1.get("businessId");
                          String name = (String) data1.get("businessName");
                          if (laborServiceCompanyService.selectLaborServiceCompanyByDutyNumAndUnitId(dutyNum,unitId,name)){
                              return Result.error("劳务公司已存在，不可重复注册");
                          }
                      }
                  }
              }catch (JsonMappingException e){}
              catch (JsonParseException e){}
              catch (IOException e){}
            }
            //原始返回数据
            return OCRUtil.ocrBizLicense(base64File);
        } catch (Exception e) {
            log.error("laborServiceCompany/ocrBizLicense: ", e);
            return Result.error(Constant.API_OPERATION_FAILED);
        }
    }



//    @RequestMapping("/ocrBizLicense")
//    public Object ocrBizLicense(@RequestParam("base64File") String base64File) {
//        try {
//            //解析之后返回的数据
//            Result result = OCRUtil.ocrBizLicense(base64File);
//
//
//            //
//            return OCRUtil.ocrBizLicense(base64File);
//        } catch (Exception e) {
//            log.error("laborServiceCompany/ocrBizLicense: ", e);
//            return Result.error(Constant.API_OPERATION_FAILED);
//        }
//    }
    /**
     * 创建劳务公司
     * @param filePath
     * @param fileName
     * @param name
     * @param bankAccount
     * @param openAccountBank
     * @param contact
     * @param contactTel
     * @param dutyNum
     * @param isBigClearPack
     * @param materialIs
     * @param unitId
     * @return
     */
    @RequestMapping("/create")
    public Object create(@RequestParam("filePath") String filePath,
                         @RequestParam("fileName") String fileName,
                         @RequestParam("name") String name,
                         @RequestParam("bankAccount") String bankAccount,
                         @RequestParam("openAccountBank") String openAccountBank,
                         @RequestParam("contact") String contact,
                         @RequestParam("contactTel") String contactTel,
                         @RequestParam("dutyNum") String dutyNum,
                         @RequestParam("isBigClearPack") int isBigClearPack,
                         @RequestParam("materialIs") int materialIs,
                         @RequestParam("unitId") String unitId) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("filePaths", filePath);
            map.put("fileNames", fileName);
            map.put("name", name);
            map.put("bankAccount", bankAccount);
            map.put("openAccountBank", openAccountBank);
            map.put("contact", contact);
            map.put("contactTel", contactTel);
            map.put("dutyNum", dutyNum);
            map.put("unitId", unitId);
            map.put("isBigClearPack", isBigClearPack);
            map.put("materialIs", materialIs);
            boolean flag;
            // 1.新增之前进行校验 名称
              flag=   laborServiceCompanyService.judgeNameOrDutyNum(unitId,name,null);
            if (flag){
                //flag  为true  说明 当前项目下有此劳务公司
                return Result.error("当前名称已存在");
            }

            // 2.新增之前进行校验  注册号
            flag=laborServiceCompanyService.judgeNameOrDutyNum(unitId,null,dutyNum);
            if (flag){
                //flag  为true  说明 当前项目下有此劳务公司
                return Result.error("当前注册号所属劳务公司已存在");
            }
            String s = HttpUtil.post(webSystemIP + "/business/laborServiceCompany/create", map);
            return JSONObject.parseObject(s);
        } catch (Exception e) {
            log.error("laborServiceCompany/create: ", e);
            return Result.error(Constant.API_OPERATION_FAILED);
        }
    }

    /**
     * 删除劳务公司
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    public Object delete(@RequestParam("id") String id) {
        try {

            Record fetch = dao.fetch("bi_labor_service_company", Cnd.where("id", "=", id));

            if (fetch != null) {
                List<Record> query = dao.query("bi_workerteam", Cnd.where("labor_service_company_id", "=", id));
                if (query != null && query.size() > 0) {
                    return Result.error("该劳务公司下含有已注册班组，禁止删除！");
                }
                int i = dao.update("bi_labor_service_company", Chain.make("delFlag", true), Cnd.where("id", "=", id));
                if (i == 1) {
                    return Result.success(Constant.API_OPERATION_SUCCESS);
                }
            }
            return Result.error("删除失败，没有该劳务公司");

        } catch (Exception e) {
            log.error("laborServiceCompany/delete: ", e);
            return Result.error(Constant.API_OPERATION_FAILED);
        }
    }
    /**
     *@author    gnaf0312@163.com
     *@create 2019/1/22 11:24
     *@Param [unitId, name]
     *@return java.lang.Object
     *@desc  根据名称验证 当前 公司下 是否有此名称劳务公司
     */
    @RequestMapping("/judgeName")
    public Object judgeName(@RequestParam("unitId") String unitId,@RequestParam("name") String name){
        try {
            boolean flag=   laborServiceCompanyService.judgeNameOrDutyNum(unitId,name,null);
            if (flag){
                //flag  为true  说明 当前项目下有此劳务公司
                return Result.error("当前名称已存在");
            }else{
                return Result.success("此名称可通过");
            }
        } catch (Exception e) {
            log.error("laborServiceCompany/judgeName: ", e);
            return Result.error(Constant.API_OPERATION_FAILED);

        }

    }

    /**
     *@author    gnaf0312@163.com
     *@create 2019/1/22 11:54
     *@Param [unitId, RegistrationCode]
     *@return java.lang.Object
     *@desc   根据注册码验证 当前 公司下 是否有此名称劳务公司
     */
    @RequestMapping("/judgeDutyNum")
    public Object judgeRegistrationCode(@RequestParam("unitId") String unitId ,@RequestParam("dutyNum") String dutyNum){
        try {
            boolean flag=laborServiceCompanyService.judgeNameOrDutyNum(unitId,null,dutyNum);
            if (flag){
                //flag  为true  说明 当前项目下有此劳务公司
                return Result.error("当前注册号所属劳务公司已存在");
            }else{
                return Result.success("此注册号可通过");
            }
        } catch (Exception e) {
            log.error("laborServiceCompany/judgeDutyNum: ", e);
            return Result.error(Constant.API_OPERATION_FAILED);

        }

    }

}
